﻿using S7.Net;
using System;
using System.Collections.Generic;
using System.Text;

namespace S7NETPLC
{
    public class S7NETFactory
    {
        private static Plc _plc;
        private static Plc _plcTemp;
        private static readonly object locker = new object();
        /// <summary>
        /// 单例Plc只有一个plc
        /// </summary>
        /// <param name="plcConfig">Plc配置</param>
        /// <returns></returns>
        public static Plc getInstance(PLCConfig plcConfig)
        {
            if (_plc == null)
            {
                lock (locker)
                {
                    if (_plc == null)
                    {
                        if (plcConfig.port.HasValue)
                        {
                            _plc = new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.port.Value, plcConfig.rack.Value, plcConfig.slot.Value);
                        }
                        else
                        {
                            _plc = new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.rack.Value, plcConfig.slot.Value);
                        }

                    }
                }
            }
            return _plc;
        }
        /// <summary>
        /// 单例Plc不同实例的plc可以相互并存
        /// </summary>
        /// <param name="plcConfig">Plc配置</param>
        /// <returns></returns>
        public static Plc PlcSingle(PLCConfig plcConfig)
        {
            if (plcConfig.port.HasValue)
            {
                _plcTemp = new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.port.Value, plcConfig.rack.Value, plcConfig.slot.Value);
            }
            else
            {
                _plcTemp = new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.rack.Value, plcConfig.slot.Value);
            }
            if (_plc == null|| _plc!= _plcTemp)
            {
                lock (locker)
                {
                    if (_plc == null || _plc != _plcTemp)
                    {
                        _plc = _plcTemp;
                    }
                }
            }
            return _plc;
        }
        /// <summary>
        /// 创建Plc
        /// </summary>
        /// <param name="plcConfig">Plc配置</param>
        /// <returns></returns>
        public static Plc Plc(PLCConfig plcConfig)
        {

            if (plcConfig.port.HasValue)
            {
                return new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.port.Value, plcConfig.rack.Value, plcConfig.slot.Value);
            }
            else
            {
                return new Plc(plcConfig.cpu, plcConfig.ip, plcConfig.rack.Value, plcConfig.slot.Value);
            }

        }
    }
}
